#include <avr/interrupt.h>
#include <avr/io.h>
#include "usart.h"


/*****************************************************************************/
void txstr(char *str)
/*
 * Description	: Transmit \0 terminated string. 
 *
 * input		: -
 * output		: *str is \0 terminated array of chars.
 * 
 * (1) ...
 */
/*****************************************************************************/
{
	while( *str != '\0' )
	{
		tx(*str);
		str++;
	}
}


/*****************************************************************************/
void tx(char data)
/*
 * Description	: Transmit single char. Waits till hardware is ready to transmit
 *
 * input		: -
 * output		: data is the character to transmit
 * 
 * (1) ...
 */
/*****************************************************************************/
{
	while((UCSRA & (1<<UDRE))==0);
	UDR = data;
}

/*****************************************************************************/
unsigned char rx(void)
/*
 * Description	: UART receive char. Blocking call
 *
 * input		: -
 * output		: Returns received char. This function waits till rx is received!
 * 
 * (1) ...
 */
/*****************************************************************************/
{
	while((UCSRA&(1<<RXC))==0);
	return UDR;
}

/*****************************************************************************/
unsigned char rx_nb(void)
/*
 * Description	: UART receive char. NON blocking call
 *
 * input		: -
 * output		: Returns 0 is no char is in the UART receive buffer else content
 *                of receive buffer (received char)
 * 
 * (1) ...
 */
/*****************************************************************************/
{
	unsigned char retval = 0;
	if( (UCSRA&(1<<RXC)) != 0 )
	{
		retval = UDR;
	}
	return retval;
}

/*****************************************************************************/
void init_uart(uint16_t baudrate)
/*
 * Description	: Init UART N81 at USART_UBBR_VALUE bps. Uart fires RX isr when
 *                char is recieved.
 *
 * input		: -
 * output		: -
 * 
 * (1) ...
 */
/*****************************************************************************/
{
	UCSRC = (0<<USBS)|(1 << UCSZ1)|(1 << UCSZ0);
	
	// Set baudrate
	switch(baudrate)
	{
		case 4800:
			UBRRL = (unsigned char)USART_UBBR_4800_VALUE;
			UBRRH = (unsigned char)(USART_UBBR_4800_VALUE>>8);		
			break;
		case 9600:
			UBRRL = (unsigned char)USART_UBBR_9600_VALUE;
			UBRRH = (unsigned char)(USART_UBBR_9600_VALUE>>8);		
			break;
		case 19200:
			UBRRL = (unsigned char)USART_UBBR_19200_VALUE;
			UBRRH = (unsigned char)(USART_UBBR_19200_VALUE>>8);		
			break;
		case 38400:
			UBRRL = (unsigned char)USART_UBBR_38400_VALUE;
			UBRRH = (unsigned char)(USART_UBBR_38400_VALUE>>8);		
			break;
		default:
			UBRRL = (unsigned char)USART_UBBR_38400_VALUE;
			UBRRH = (unsigned char)(USART_UBBR_38400_VALUE>>8);		
			break;
	}

	UCSRB = (1<<RXEN) | (1<<TXEN);
	
	// Enable UART RX interrupts
	UCSRB |= (1<<RXCIE);
}
